import {
    HTTP
} from '../utils/http'

class ClassicModel extends HTTP {
  getLatest (sCallback) {
    this.request({
      url: 'classic/latest',
      success: (res) => {
        sCallback(res)
        this._setLatestIndex(res.index)
        wx.setStorageSync(this._getKey(res.index), res)
      }
    })
  }

  getClassic (index, nextOrPrevious, sCallback) {
    const key = nextOrPrevious === 'next' ? this._getKey(index + 1) : this._getKey(index - 1)
    const classic = wx.getStorageSync(key)
    if (!classic) {
      this.request({
        url: `classic/${index}/${nextOrPrevious}`,
        success: (res) => {
          wx.setStorageSync(this._getKey(res.index), res)
          sCallback(res)
        }
      })
    } else {
      sCallback(classic)
    }
  }

  getMyFavor (success) {
    const params = {
      url: 'classic/favor',
      success: success
    }
    this.request(params)
  }

  getById (cid, type, success) {
    let params = {
      url: `classic/${type}/${cid}`,
      success: success
    }
    this.request(params)
  }

  isFirst (index) {
    return index === 1
  }

  isLatest (index) {
    const latestIndex = this._getLatestIndex()
    return latestIndex === index
  }

  _setLatestIndex (index) {
    wx.setStorageSync('latest', index)
  }

  _getLatestIndex () {
    const index = wx.getStorageSync('latest')
    return index
  }

  _getKey (index) {
    const key = `classic-${index}`
    return key
  }
}

export {
    ClassicModel
}
